package com.kt.opc.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.sdk.client.api.identity.UsernameProvider;
import org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.Security;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint;

public class OpcUtil {

    static {
        // Required for SecurityPolicy.Aes256_Sha256_RsaPss
        Security.addProvider(new BouncyCastleProvider());
    }



    public static OpcUaClient createClient(String url, String name, String pwd) throws Exception {

        Path securityTempDir = Paths.get(System.getProperty("java.io.tmpdir"), "security");
        Files.createDirectories(securityTempDir);
        if (!Files.exists(securityTempDir)) {
            throw new Exception("unable to create security dir: " + securityTempDir);
        }

        KeyStoreLoader loader = new KeyStoreLoader().load(securityTempDir);


        return OpcUaClient.create(url, endpoints ->
                endpoints.stream()
                        // .filter( e -> true)
                        .findFirst(), configBuilder ->
                configBuilder
                        .setApplicationName(LocalizedText.english("opc"))
                        .setApplicationUri("urn:eclipse:milo:examples:client")
                        .setCertificate(loader.getClientCertificate())
                        .setKeyPair(loader.getClientKeyPair())
                        //.setIdentityProvider(new AnonymousProvider())//无用户名 密码
                        .setIdentityProvider(new UsernameProvider(name, pwd))//
                        .setRequestTimeout(uint(5000))
                        .build());
    }



}
